package com.gitee.flyzing.jxt.component;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yaoguangyao
 * @Date 2021年6月29日
 */
public class JXTSheet {
	private String sheetName = "";
	private List<JXTRow> jxtRows = new ArrayList<>();
	private Map<Integer, Integer> columnWidths = new HashMap<>();
	private List<Integer> columnHeights = new ArrayList<>();

	public void createXSSFSheet(XSSFWorkbook xssfWorkbook, int index) {
		XSSFSheet xssfSheet = xssfWorkbook.createSheet();
		for (int i = 0; i < jxtRows.size(); i++) {
			JXTRow jxtRow = jxtRows.get(i);
			jxtRow.createXSSFRow(xssfSheet, i);
		}
		//设置列换
		for (Map.Entry<Integer, Integer> entry : columnWidths.entrySet()) {
			xssfSheet.setColumnWidth(entry.getKey(), entry.getValue());
		}
		xssfWorkbook.setSheetName(index, sheetName); //设置sheet名称
	}

	public static JXTSheet createJXTSheet(XSSFSheet sheet, String sheetName, Object datas) {
		JXTSheet jxtSheet = new JXTSheet();
		jxtSheet.setSheetName(sheetName);
		jxtSheet.setColumnWidths(sheet);

		JXTEachRow jxtEachRow = null;
		for (Row row : sheet) {
			JXTRow jxtRow = JXTRow.createJXTRow(row, datas);
			if (jxtEachRow != null) {
				List<JXTRow> itemRows = jxtEachRow.getJXTRows(row);
				if (itemRows != null && itemRows.size() > 0) {
					jxtSheet.addAll(itemRows);
				}
				jxtEachRow = null; //foreach结束
			} else if (jxtRow instanceof JXTEachRow) {
				jxtEachRow = (JXTEachRow) jxtRow;
			} else if (jxtRow != null){
				jxtSheet.add(jxtRow);
			}
		}
		return jxtSheet;
	}

	public void setColumnWidths(XSSFSheet sheet) {
		if (sheet != null && sheet.rowIterator().hasNext()) {
			Row row = sheet.getRow(0);
			for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
				int width = sheet.getColumnWidth(i);
				columnWidths.put(i, width);
			}
		}
	}

	public String getSheetName() {
		return sheetName;
	}

	public void setSheetName(String sheetName) {
		this.sheetName = sheetName;
	}

	public void add(JXTRow jxtRow) {
		this.jxtRows.add(jxtRow);
	}

	public void addAll(List<JXTRow> jxtRows) {
		this.jxtRows.addAll(jxtRows);
	}

	public List<JXTRow> getJxtRows() {
		return jxtRows;
	}

	public void setJxtRows(List<JXTRow> jxtRows) {
		this.jxtRows = jxtRows;
	}
}
